import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'
import websocketService from './services/websocketService'

import App from './App.vue'
import router from './router'

// 初始化WebSocket连接
const initWebSocket = () => {
  const token = localStorage.getItem('token')
  if (!token) {
    console.log('用户未登录，不初始化WebSocket')
    return
  }
  
  try {
    // 尝试获取用户ID
    const userData = JSON.parse(localStorage.getItem('user'))
    if (userData && userData.id) {
      console.log('应用启动时连接WebSocket，用户ID:', userData.id)
      websocketService.connect(userData.id)
    } else {
      // 尝试从JWT解析用户ID
      try {
        const base64Url = token.split('.')[1]
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
        const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
        }).join(''))
        
        const payload = JSON.parse(jsonPayload)
        if (payload && payload.sub) {
          console.log('应用启动时从JWT解析用户ID:', payload.sub)
          websocketService.connect(payload.sub)
          
          // 保存用户ID到本地存储
          localStorage.setItem('user', JSON.stringify({ id: payload.sub }))
        }
      } catch (jwtError) {
        console.error('解析JWT失败:', jwtError)
      }
    }
  } catch (error) {
    console.error('连接WebSocket失败:', error)
  }
}

// 应用启动时初始化WebSocket
initWebSocket()

const app = createApp(App)

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(createPinia())
app.use(router)
app.use(ElementPlus)

app.mount('#app')
